package cn.zswltech.gruul.web.api.util;

import cn.zswltech.gruul.common.constant.UserConstants;
import cn.zswltech.gruul.common.dal.vo.AccountVO;

import cn.zswltech.gruul.common.entity.UserDO;
import cn.zswltech.gruul.common.util.*;
import cn.zswltech.gruul.domain.entity.CheckResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.regex.Pattern;


@Slf4j
public class AccountUtil {
    

    /**
     * 要求密码8-18位，由 数字+大写字母+小写字母+特殊字符 组成
     */
    private static final String DEFAULT_PWD_REGEX = "(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\\W_]).{8,18}";

    /**
     * 获取登录信息
     *
     * @return
     */
    public static AccountVO getLoginInfo() {
        // FIX ME
        if (Boolean.TRUE.equals(WhiteListUtil.getWhiteListFlag())) {
            AccountVO accountVO = new AccountVO();
            accountVO.setAccount("admin");
            accountVO.setId(3L);
            return accountVO;
        }
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes == null) {
                return null;
            }
            HttpServletRequest request = requestAttributes.getRequest();
            String wlToken = CookieUtils.getWlToken(request);
            return getLoginInfo(wlToken);
        } catch (Exception e) {
            log.error("getLoginInfo error", e);
        }
        return null;
    }

    /**
     * 获取登录信息
     * @return
     */
    public static AccountVO getLoginInfo(String wlToken){
        if (StringUtils.isEmpty(wlToken)) {
            return null;
        }
        CheckResult checkResult = JwtUtils.validateJWT(wlToken);
        if (!checkResult.isSuccess()) {
            return null;
        }
        AccountVO accountVO = new AccountVO();
        accountVO.setAccount(checkResult.getClaims().get("sub").toString());
        accountVO.setId(((Integer)checkResult.getClaims().get("id")).longValue());
        accountVO.setExpiration(checkResult.getClaims().get("exp").toString());
        return accountVO;
    }

    public static String getCurrentUserToken() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        return CookieUtils.getWlToken(request);
    }

    public static String genSalt() {
        return UUIDUtil.genUuid();
    }

    /**
     * 生成密码
     *
     * @param pwd  明文密码
     * @param salt
     * @return
     */
    public static String genPwd(String pwd, String salt) {
        return MD5Util.MD5(MD5Util.MD5(pwd) + salt);
    }

    /**
     * @param userIndb 数据中查询出的用户
     * @param pwd      明文密码
     * @return
     */
    public static boolean checkPwd(UserDO userIndb, String pwd) {
        return genPwd(pwd, userIndb.getSalt()).equals(userIndb.getPwd());
    }

    /**
     * 解密前端AES加密密码
     * encodePwd
     *
     * @param encodePwd
     * @return
     */
    public static String decodePwd(String encodePwd) {
        // 将base64格式转换成十六进制
        encodePwd = AESUtil.parseByte2HexStr(Base64Utils.decode(encodePwd.getBytes(Charset.defaultCharset())));
        // key和ip偏移量跟前端约定好
        return AESUtil.decrypt(encodePwd, "sdJ2HjFyneCMFxz3", "efamgO9jaLHfb5cv");
    }

    /**
     * 创建一个用户
     *
     * @return
     */
    public static UserDO genUser(String account, String pwd) {
        UserDO user = new UserDO();
        user.setAccount(account);
        user.setPwd(pwd); // 设置一个随机密码
        user.setSalt(AccountUtil.genSalt());
        user.setPwd(MD5Util.MD5(user.getPwd() + user.getSalt()));
        user.setStatus(UserConstants.ACCOUNT_STATUS_DEFAULT);
        // 默认过期时间为2年
        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.YEAR, 2);
        user.setExpiration(ca.getTime());
        return user;
    }

    /**
     * 校验密码,密码必须同时包含6~18位数字、大小写字母及特殊字符
     *
     * @param pwd
     * @return boolean
     * @author xuluquan
     * @date 2020-04-03 13:43
     */
    public static boolean validatePwd(String pwd, String passwordRegex) {
        if (StringUtils.isBlank(pwd) || pwd.length() < 8 || pwd.length() > 18) {
            return false;
        }
        return Pattern.matches(StringUtils.isNotBlank(passwordRegex) ? passwordRegex : DEFAULT_PWD_REGEX, pwd);
    }

    public static String getSalt(String account, String encryptPassword, String origin) {
        String sign = String.format("%s_%s_%s", account, encryptPassword, origin);
        String md5Sign = MD5Util.MD5(sign).substring(0, 32);
        return md5Sign;
    }


    public static String getAccount() {
        try {
            getLoginInfo().getAccount();
        } catch (Exception e) {
            log.error("获取账户失败", e);
        }
        return null;
    }
}
